package com.hxzy.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.annon.Log;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.enums.BusinessType;
import com.hxzy.common.exception.ShopException;
import com.hxzy.common.vo.R;
import com.hxzy.dto.system.SysMenuSearchDTO;
import com.hxzy.entity.system.SysMenu;
import com.hxzy.service.system.SysMenuService;
import com.hxzy.vo.SysMenuVO;
import com.hxzy.vo.TreeSelect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "菜单角色API")
@RestController
@RequestMapping(value = "/api/menu")
public class SysMenuController extends BaseController {


    @Autowired
    private SysMenuService sysMenuService;

    @PreAuthorize("@ss.hasAuthority('system:menu:list')")
    @ApiOperation(value = "根据条件查询菜单")
    @GetMapping(value = "/data")
    public R search(SysMenuSearchDTO sysMenuSearchDTO){
        List<SysMenu> sysMenuList = this.sysMenuService.selectMenuList(sysMenuSearchDTO);
        //构造父子节点树
        List<SysMenuVO> menuVOList= this.sysMenuService.buildMenu(sysMenuList);
        //前端
        return  super.listToPageVO(menuVOList);
    }


    @PreAuthorize(value = "@ss.hasAuthority('system:menu:query')")
    @ApiOperation(value = "加载树型菜单数据")
    @GetMapping(value = "/treeselect")
    public R menuTreeSelect(){
        //根据条件查询菜单，这里没有给对象赋值，相当于全查询
        List<SysMenu> menus = sysMenuService.selectMenuList(new SysMenuSearchDTO());
        //把SysMenu转换成树型节点
        List<TreeSelect> treeSelects=this.sysMenuService.buildMenuTreeSelect(menus);
        return R.okHasData(treeSelects);
    }

    @ApiOperation(value = "加载对应角色菜单列表树")
    @GetMapping(value = "/rolemenu/{roleId}")
    public R roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        //根据条件查询菜单，这里没有给对象赋值，相当于全查询
        List<SysMenu> menus = sysMenuService.selectMenuList(new SysMenuSearchDTO());

        //根据该角色id拥有的菜单
        List<Long> checkMenu=  this.sysMenuService.selectMenuListByRoleId(roleId);

        //把SysMenu转换成树型节点
        List<TreeSelect> treeSelects=this.sysMenuService.buildMenuTreeSelect(menus);

        //组装数据到前端
        Map<String,Object> data=new HashMap<>();
        data.put("checkedKeys", checkMenu);
        data.put("menus", treeSelects);

        return R.okHasData(data);
    }


    @Log(title = "菜单管理",businessType = BusinessType.INSERT)
    @PreAuthorize(value = "@ss.hasAuthority('system:menu:add')")
    @PostMapping
    @ApiOperation(value = "新增菜单")
    public R  add(@RequestBody @Valid SysMenu sysMenu) {
        this.customerValidator(sysMenu);

        boolean save = this.sysMenuService.save(sysMenu);
        return super.toR(save);
    }


    @PreAuthorize(value = "@ss.hasAuthority('system:menu:query')")
    @ApiOperation(value = "根据主键查询")
    @GetMapping("/{menuId}")
    public R findById(@PathVariable(value = "menuId") Long menuId){
         SysMenuVO  sysMenuVO=this.sysMenuService.findById(menuId);
         if(sysMenuVO==null){
             return R.build(AckCode.NOT_FOUND_DATA);
         }

        return  R.okHasData(sysMenuVO);
    }

    @Log(title = "菜单管理",businessType = BusinessType.UPDATE)
    @PreAuthorize(value = "@ss.hasAuthority('system:menu:edit')")
    @PutMapping
    @ApiOperation(value = "修改菜单")
    public R  edit(@RequestBody @Valid SysMenu sysMenu) {
        this.customerValidator(sysMenu);
        boolean save = this.sysMenuService.updateById(sysMenu);
        return super.toR(save);
    }

    /**
     * 自定义验证
     * @param sysMenu
     */
    private void customerValidator(SysMenu sysMenu){
        //做自定义的业务逻辑判断
        // 目录  或者   菜单 ,路由地址 必须要有值
        if(sysMenu.getMenuType().equals("M") || sysMenu.getMenuType().equals("C")){
            if(StrUtil.isBlank(sysMenu.getPath())){
                throw new ShopException("路由地址不允许为空");
            }
        }

        // 组件地址， sysMenu.getMenuType().equals("C") 才要判断
        if( sysMenu.getMenuType().equals("C")){
            if(StrUtil.isBlank(sysMenu.getComponent())){
                throw new ShopException("组件地址不允许为空");
            }
        }

        // 菜单和按钮才有权限
        if( sysMenu.getMenuType().equals("C") || sysMenu.getMenuType().equals("F")){
            if(StrUtil.isBlank(sysMenu.getPerms())){
                throw new ShopException("权限标识不允许为空");
            }
        }
    }
}
